package org.jeese.common.shiro;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpStatus;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import net.sf.json.JSONObject;
/**
 * @Description:shiro登录过滤
 * @Package:org.jeese.security
 * @author:wubc
 * @version:1.0
 * @date:2017年10月30日-下午2:26:54
 * @Copyright:2017 Inc. All rights reserved.
 */
public class ShiroLoginFilter extends AuthorizationFilter  {
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		Subject subject = getSubject(request, response); 
		//String url = getPathWithinApplication(request);
		//如果已经登录授权或者是登录请求则跳过，否则跳转登录
		if (subject.isAuthenticated() || isLoginRequest(request, response)) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		saveRequest(request);
		if (isAjax(WebUtils.toHttp(request))) {
			// 登录超时状态码301，
			WebUtils.toHttp(response).sendError(HttpStatus.SC_MOVED_PERMANENTLY);
		} else {
			//httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.html");
			//WebUtils.issueRedirect(request, response, "login.html");
			// 保存Request和Response 到登录后的链接
			saveRequestAndRedirectToLogin(request, response);
		}
		return false;
	}

	/**
	 * 是否是ajax请求
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request) {
		if (request.getHeader("x-requested-with") != null
				&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 使用 response 输出JSON
	 * @param hresponse
	 * @param resultMap
	 * @throws IOException
	 */
	public static void out(ServletResponse response, Map<String, String> resultMap) {
		PrintWriter out = null;
		try {
			// 设置编码
			response.setCharacterEncoding("UTF-8");
			// 设置返回类型
			response.setContentType("application/json");
			out = response.getWriter();
			// 输出
			out.println(JSONObject.fromObject(resultMap).toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != out) {
				out.flush();
				out.close();
			}
		}
	}
	
}
